import re
from django.core import exceptions
from django.db import models
from django.db.models.fields import EmailField
from django.utils.functional import empty
from rest_framework import serializers
from rest_framework.fields import ReadOnlyField
from rest_framework_simplejwt.serializers import PasswordField
from .models import Tenant, User
class RegistrationSerializer(serializers.Serializer):
    email=serializers.EmailField()
    password=PasswordField()
    first_name=serializers.CharField(required=False,default='')
    last_name=serializers.CharField(required=False,default='')
    def validate_email(self, value):
        user_schema_name=User.get_default_schema
        try:
            Tenant.objects.get(schema_name=user_schema_name)
            raise exceptions.ValidationError(f'{value}已经存在')
        except Tenant.DoesNotExist:
            return value
        
class UserSerializer(serializers.ModelSerializer):
    tenant=serializers.StringRelatedField()
    id=serializers.ReadOnlyField()
    roles=serializers.StringRelatedField(many=True)
    class Meta:
        model=User
        fields=(
            'id',
            'email',
            'first_name',
            'last_name',
            'tenant',
            'roles',
            'created'
        )